<template>
  <div v-if="visible" class="er-modal-overlay" @click.self="handleClose">
    <div class="er-modal-container">
      <div class="er-modal-header">
        <h3>📊 AI生成数据库表ER图</h3>
        <button class="close-btn" @click="handleClose">&times;</button>
      </div>
      
      <div class="er-modal-body">
        <div v-if="loading" class="loading">
          <div class="spinner"></div>
          <span>正在分析数据库表关系...</span>
        </div>
        
        <div v-else-if="error" class="error-message">
          <span class="error-icon">⚠️</span>
          {{ error }}
        </div>
        
        <div v-else-if="erResult" class="er-container">
          <!-- ER图工具栏 -->
          <div class="er-toolbar">
            <div class="toolbar-left">
              <span class="table-count">{{ erResult.tables.length }} 个表</span>
              <span class="relation-count">{{ erResult.relationships.length }} 个关系</span>
            </div>
            <div class="toolbar-right">
              <span class="zoom-info">{{ Math.round(zoom * 100) }}%</span>
              <button class="tool-btn" @click="resetView" title="重置视图">
                🔄 重置
              </button>
              <button class="tool-btn" @click="zoomIn" title="放大" :disabled="zoom >= 3">
                🔍+ 放大
              </button>
              <button class="tool-btn" @click="zoomOut" title="缩小" :disabled="zoom <= 0.1">
                🔍- 缩小
              </button>
            </div>
          </div>
          
          <!-- ER图画布 -->
          <div class="er-canvas-container">
            <svg 
              ref="erCanvas" 
              class="er-canvas"
              :viewBox="`0 0 ${canvasWidth} ${canvasHeight}`"
              @mousedown="startPan"
              @wheel="handleWheel"
            >
              <!-- 变换容器 -->
              <g :transform="transformString">
                <!-- 关系线 -->
                <g class="relationships">
                  <g v-for="(rel, index) in erResult.relationships" :key="'rel-' + index">
                    <line
                      :x1="getTablePosition(rel.fromTable).x + tableWidth/2"
                      :y1="getTablePosition(rel.fromTable).y + tableHeight"
                      :x2="getTablePosition(rel.toTable).x + tableWidth/2"
                      :y2="getTablePosition(rel.toTable).y"
                      :class="'relation-line ' + rel.type"
                      :stroke-width="2"
                    />
                    <!-- 关系标签 -->
                    <text
                      :x="(getTablePosition(rel.fromTable).x + getTablePosition(rel.toTable).x + tableWidth) / 2"
                      :y="(getTablePosition(rel.fromTable).y + getTablePosition(rel.toTable).y + tableHeight) / 2"
                      class="relation-label"
                      text-anchor="middle"
                    >
                      {{ rel.label }}
                    </text>
                  </g>
                </g>
                
                <!-- 数据库表 -->
                <g class="tables">
                  <g 
                    v-for="(table, index) in erResult.tables" 
                    :key="'table-' + table.name"
                    :transform="`translate(${getTablePosition(table.name).x}, ${getTablePosition(table.name).y})`"
                    class="table-group"
                    @mousedown="startDragTable($event, table.name)"
                  >
                    <!-- 表框 -->
                    <rect
                      :width="tableWidth"
                      :height="tableHeight"
                      class="table-rect"
                      :class="{ 'table-selected': selectedTable === table.name }"
                      @click="selectTable(table.name)"
                    />
                    
                    <!-- 表头 -->
                    <rect
                      :width="tableWidth"
                      height="30"
                      class="table-header"
                    />
                    
                    <!-- 表名 -->
                    <text
                      :x="tableWidth/2"
                      y="20"
                      class="table-name"
                      text-anchor="middle"
                    >
                      {{ table.name }}
                    </text>
                    
                    <!-- 表注释 -->
                    <text
                      v-if="table.comment"
                      :x="tableWidth/2"
                      y="45"
                      class="table-comment"
                      text-anchor="middle"
                    >
                      {{ table.comment }}
                    </text>
                    
                    <!-- 字段列表 -->
                    <g class="table-fields">
                      <g 
                        v-for="(field, fieldIndex) in table.fields.slice(0, 8)" 
                        :key="field.name"
                        :transform="`translate(5, ${60 + fieldIndex * 20})`"
                      >
                        <text
                          x="0"
                          y="15"
                          class="field-name"
                          :class="{ 'primary-key': field.isPrimaryKey, 'foreign-key': field.isForeignKey }"
                        >
                          {{ field.isPrimaryKey ? '🔑' : field.isForeignKey ? '🔗' : '•' }} {{ field.name }}
                        </text>
                        <text
                          :x="tableWidth - 10"
                          y="15"
                          class="field-type"
                          text-anchor="end"
                        >
                          {{ field.type }}
                        </text>
                      </g>
                      <text
                        v-if="table.fields.length > 8"
                        x="5"
                        :y="60 + 8 * 20 + 15"
                        class="field-more"
                      >
                        ... 还有 {{ table.fields.length - 8 }} 个字段
                      </text>
                    </g>
                  </g>
                </g>
              </g>
            </svg>
          </div>
          
          <!-- 表详情面板 -->
          <div v-if="selectedTable" class="table-detail-panel">
            <div class="panel-header">
              <h4>{{ selectedTable }} 表详情</h4>
              <button class="panel-close" @click="selectedTable = null">&times;</button>
            </div>
            <div class="panel-content">
              <div class="selected-table-info">
                <div v-for="field in getSelectedTableInfo().fields" :key="field.name" class="field-detail">
                  <span class="field-icon">
                    {{ field.isPrimaryKey ? '🔑' : field.isForeignKey ? '🔗' : '•' }}
                  </span>
                  <span class="field-name">{{ field.name }}</span>
                  <span class="field-type">{{ field.type }}</span>
                  <span v-if="field.comment" class="field-comment">{{ field.comment }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="no-data">
          <div class="no-data-icon">📊</div>
          <div class="no-data-text">暂无ER图数据</div>
          <div class="no-data-desc">请重新尝试生成</div>
        </div>
      </div>
      
      <div class="er-modal-footer">
        <button class="btn btn-close" @click="handleClose">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ErDiagramDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    error: {
      type: String,
      default: null
    },
    erResult: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      canvasWidth: 1200,
      canvasHeight: 800,
      tableWidth: 200,
      tableHeight: 220,
      selectedTable: null,
      tablePositions: {},
      dragState: {
        isDragging: false,
        tableName: null,
        startX: 0,
        startY: 0,
        startTableX: 0,
        startTableY: 0
      },
      panState: {
        isPanning: false,
        startX: 0,
        startY: 0,
        startPanX: 0,
        startPanY: 0
      },
      zoom: 1,
      panX: 0,
      panY: 0
    }
  },
  watch: {
    erResult: {
      handler(newResult) {
        if (newResult && newResult.tables) {
          this.initializeTablePositions()
        }
      },
      immediate: true
    }
  },
  computed: {
    transformString() {
      return `translate(${this.panX}, ${this.panY}) scale(${this.zoom})`
    }
  },
  methods: {
    handleClose() {
      this.$emit('close')
      this.selectedTable = null
    },
    
    initializeTablePositions() {
      if (!this.erResult || !this.erResult.tables) return
      
      const tables = this.erResult.tables
      const cols = Math.ceil(Math.sqrt(tables.length))
      const spacing = 250
      
      tables.forEach((table, index) => {
        const row = Math.floor(index / cols)
        const col = index % cols
        this.$set(this.tablePositions, table.name, {
          x: col * spacing + 50,
          y: row * spacing + 100
        })
      })
    },
    
    getTablePosition(tableName) {
      return this.tablePositions[tableName] || { x: 0, y: 0 }
    },
    
    selectTable(tableName) {
      this.selectedTable = this.selectedTable === tableName ? null : tableName
    },
    
    getSelectedTableInfo() {
      if (!this.selectedTable || !this.erResult) return { fields: [] }
      return this.erResult.tables.find(t => t.name === this.selectedTable) || { fields: [] }
    },
    
    startDragTable(event, tableName) {
      event.stopPropagation()
      const rect = this.$refs.erCanvas.getBoundingClientRect()
      
      this.dragState = {
        isDragging: true,
        tableName: tableName,
        startX: event.clientX - rect.left,
        startY: event.clientY - rect.top,
        startTableX: this.getTablePosition(tableName).x,
        startTableY: this.getTablePosition(tableName).y
      }
      
      document.addEventListener('mousemove', this.handleDragTable)
      document.addEventListener('mouseup', this.stopDragTable)
    },
    
    handleDragTable(event) {
      if (!this.dragState.isDragging) return
      
      const rect = this.$refs.erCanvas.getBoundingClientRect()
      const currentX = event.clientX - rect.left
      const currentY = event.clientY - rect.top
      
      const deltaX = currentX - this.dragState.startX
      const deltaY = currentY - this.dragState.startY
      
      const newX = Math.max(0, Math.min(this.canvasWidth - this.tableWidth, this.dragState.startTableX + deltaX))
      const newY = Math.max(0, Math.min(this.canvasHeight - this.tableHeight, this.dragState.startTableY + deltaY))
      
      this.$set(this.tablePositions, this.dragState.tableName, {
        x: newX,
        y: newY
      })
    },
    
    stopDragTable() {
      this.dragState.isDragging = false
      document.removeEventListener('mousemove', this.handleDragTable)
      document.removeEventListener('mouseup', this.stopDragTable)
    },
    
    startPan(event) {
      if (this.dragState.isDragging) return
      
      event.preventDefault()
      const rect = this.$refs.erCanvas.getBoundingClientRect()
      
      this.panState = {
        isPanning: true,
        startX: event.clientX - rect.left,
        startY: event.clientY - rect.top,
        startPanX: this.panX,
        startPanY: this.panY
      }
      
      document.addEventListener('mousemove', this.handlePanMove)
      document.addEventListener('mouseup', this.stopPan)
    },
    
    handlePanMove(event) {
      if (!this.panState.isPanning) return
      
      const rect = this.$refs.erCanvas.getBoundingClientRect()
      const currentX = event.clientX - rect.left
      const currentY = event.clientY - rect.top
      
      const deltaX = currentX - this.panState.startX
      const deltaY = currentY - this.panState.startY
      
      this.panX = this.panState.startPanX + deltaX
      this.panY = this.panState.startPanY + deltaY
    },
    
    stopPan() {
      this.panState.isPanning = false
      document.removeEventListener('mousemove', this.handlePanMove)
      document.removeEventListener('mouseup', this.stopPan)
    },
    
    handleWheel(event) {
      event.preventDefault()
      
      const rect = this.$refs.erCanvas.getBoundingClientRect()
      const mouseX = event.clientX - rect.left
      const mouseY = event.clientY - rect.top
      
      // 计算鼠标在SVG坐标系中的位置
      const svgX = (mouseX - this.panX) / this.zoom
      const svgY = (mouseY - this.panY) / this.zoom
      
      // 缩放增量
      const delta = event.deltaY > 0 ? 0.9 : 1.1
      const newZoom = Math.max(0.1, Math.min(3, this.zoom * delta))
      
      // 调整平移以保持鼠标位置不变
      this.panX = mouseX - svgX * newZoom
      this.panY = mouseY - svgY * newZoom
      this.zoom = newZoom
    },
    
    zoomIn() {
      const centerX = this.canvasWidth / 2
      const centerY = this.canvasHeight / 2
      
      // 计算中心点在SVG坐标系中的位置
      const svgCenterX = (centerX - this.panX) / this.zoom
      const svgCenterY = (centerY - this.panY) / this.zoom
      
      const newZoom = Math.min(3, this.zoom * 1.2)
      
      // 调整平移以保持中心点不变
      this.panX = centerX - svgCenterX * newZoom
      this.panY = centerY - svgCenterY * newZoom
      this.zoom = newZoom
    },
    
    zoomOut() {
      const centerX = this.canvasWidth / 2
      const centerY = this.canvasHeight / 2
      
      // 计算中心点在SVG坐标系中的位置
      const svgCenterX = (centerX - this.panX) / this.zoom
      const svgCenterY = (centerY - this.panY) / this.zoom
      
      const newZoom = Math.max(0.1, this.zoom / 1.2)
      
      // 调整平移以保持中心点不变
      this.panX = centerX - svgCenterX * newZoom
      this.panY = centerY - svgCenterY * newZoom
      this.zoom = newZoom
    },
    
    resetView() {
      this.zoom = 1
      this.panX = 0
      this.panY = 0
      this.initializeTablePositions()
    }
  },
  
  beforeDestroy() {
    if (this.dragState.isDragging) {
      document.removeEventListener('mousemove', this.handleDragTable)
      document.removeEventListener('mouseup', this.stopDragTable)
    }
    if (this.panState.isPanning) {
      document.removeEventListener('mousemove', this.handlePanMove)
      document.removeEventListener('mouseup', this.stopPan)
    }
  }
}
</script>

<style scoped>
.er-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(5px);
}

.er-modal-container {
  background: white;
  border-radius: 12px;
  width: 95vw;
  height: 90vh;
  max-width: 1400px;
  max-height: 900px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}

.er-modal-header {
  padding: 20px 25px;
  background: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.er-modal-header h3 {
  margin: 0;
  color: #374151;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6b7280;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.er-modal-body {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #6b7280;
}

.spinner {
  display: inline-block;
  width: 32px;
  height: 32px;
  border: 3px solid #e5e7eb;
  border-top-color: #4f46e5;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #dc2626;
  font-size: 16px;
  gap: 10px;
}

.error-icon {
  font-size: 24px;
}

.er-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.er-toolbar {
  padding: 15px 20px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  gap: 20px;
  align-items: center;
}

.table-count, .relation-count {
  font-size: 14px;
  color: #6b7280;
}

.toolbar-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.zoom-info {
  font-size: 13px;
  color: #4b5563;
  font-weight: 500;
  min-width: 50px;
  text-align: center;
}

.tool-btn {
  background: white;
  border: 1px solid #d1d5db;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.tool-btn:hover:not(:disabled) {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.tool-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.er-canvas-container {
  flex: 1;
  overflow: hidden;
  position: relative;
  background: #fefefe;
}

.er-canvas {
  width: 100%;
  height: 100%;
  cursor: grab;
}

.er-canvas:active {
  cursor: grabbing;
}

/* SVG样式 */
.table-group {
  cursor: move;
}

.table-rect {
  fill: white;
  stroke: #d1d5db;
  stroke-width: 2;
  rx: 8;
}

.table-rect.table-selected {
  stroke: #4f46e5;
  stroke-width: 3;
}

.table-header {
  fill: #4f46e5;
  rx: 8 8 0 0;
}

.table-name {
  font-size: 14px;
  font-weight: 600;
  fill: white;
}

.table-comment {
  font-size: 12px;
  fill: #6b7280;
}

.field-name {
  font-size: 12px;
  fill: #374151;
}

.field-name.primary-key {
  fill: #dc2626;
  font-weight: 600;
}

.field-name.foreign-key {
  fill: #059669;
  font-weight: 600;
}

.field-type {
  font-size: 11px;
  fill: #6b7280;
}

.field-more {
  font-size: 11px;
  fill: #9ca3af;
  font-style: italic;
}

.relation-line {
  stroke: #6b7280;
}

.relation-line.one-to-one {
  stroke: #059669;
}

.relation-line.one-to-many {
  stroke: #dc2626;
}

.relation-line.many-to-many {
  stroke: #7c3aed;
}

.relation-label {
  font-size: 11px;
  fill: #4b5563;
  font-weight: 500;
}

.table-detail-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 300px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
  max-height: calc(100% - 40px);
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 15px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.panel-close {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  color: #6b7280;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.field-detail {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
  font-size: 13px;
}

.field-detail:last-child {
  border-bottom: none;
}

.field-icon {
  width: 16px;
  text-align: center;
}

.field-name {
  font-weight: 500;
  color: #374151;
  min-width: 80px;
}

.field-type {
  color: #6b7280;
  font-family: 'Courier New', monospace;
  min-width: 60px;
}

.field-comment {
  color: #059669;
  font-size: 12px;
  flex: 1;
}

.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #9ca3af;
}

.no-data-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-data-text {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
}

.no-data-desc {
  font-size: 14px;
}

.er-modal-footer {
  padding: 20px 25px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-close {
  background: #6b7280;
  color: white;
}

.btn-close:hover {
  background: #4b5563;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .er-modal-container {
    width: 100vw;
    height: 100vh;
    border-radius: 0;
  }
  
  .table-detail-panel {
    width: 250px;
  }
}
</style>